package com.example.wordpress;

import java.util.Arrays;
import java.util.List;

import com.facebook.*;
import com.facebook.model.*;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class LoginController implements OnClickListener {	
	private final Activity activity;
//	public final LoginModel loginModel;
	private final LoginView loginView;
	
	private Session.StatusCallback estadoCallback = new SessionStatusCallback();
	private static final List<String> PERMISOS = Arrays.asList("publish_actions");
	private String TAG = "TAG ||---> LoginController";
	
//	public LoginController(Activity a, LoginModel m, LoginView v, Bundle instanciaEstadoGuardada) {
	public LoginController(Activity a, LoginView v, Bundle instanciaEstadoGuardada) {
		activity = a;
//		loginModel = m;
		loginView = v;
		
		loginView.setAuthButtonVisibility(0);
		Session sesion = Session.getActiveSession();
		if (sesion == null) {
			if (instanciaEstadoGuardada != null) {
				sesion = Session.restoreSession(activity, null, estadoCallback, instanciaEstadoGuardada);
			}
			if (sesion == null) {
				sesion = new Session(activity);
			}
			Session.setActiveSession(sesion);
			if (sesion.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
				sesion.openForRead(new Session.OpenRequest(activity).setCallback(estadoCallback));
				Session.NewPermissionsRequest nuevosPermisos = new Session.NewPermissionsRequest(activity, PERMISOS);
	            sesion.requestNewPublishPermissions(nuevosPermisos);
			}
		}
		
		actualizarView();
		loginView.setAuthButtonEnabled(true);
	}
	
	@SuppressWarnings("deprecation")
	private void actualizarView() {
		Session sesion = Session.getActiveSession();
		if (sesion.isOpened()) {
        	Log.i(TAG,"TAG ||---> Access Token"+ sesion.getAccessToken());
			Request.executeMeRequestAsync(sesion,
			new Request.GraphUserCallback() {
				@Override
				public void onCompleted(GraphUser usuario,Response respuesta) {
					if (usuario != null) {
						Log.i(TAG,"TAG ||---> User ID "+ usuario.getId());
						Log.i(TAG,"TAG ||---> Email "+ usuario.asMap().get("email"));
						loginView.setTag(activity.getString(R.string.logout_text));
						loginView.getUserPhoto().setProfileId(usuario.getId());
						loginView.setUserName("Vinculado con: " + usuario.getName() + ".");
					}
					if (respuesta.getError() != null || usuario == null) {
						Log.i(TAG,"TAG ||---> CERRADO");
						loginView.setTag(activity.getString(R.string.login_text));
						loginView.getUserPhoto().setProfileId(null);
						loginView.setUserName(activity.getString(R.string.username));
		            }					
				}
			});
		} else {
			Log.i(TAG,"TAG ||---> CERRADO");
			loginView.setTag(activity.getString(R.string.login_text));
			loginView.getUserPhoto().setProfileId(null);
			loginView.setUserName(activity.getString(R.string.username));
        }
		activity.setResult(Activity.RESULT_OK, null);
		activity.finish();
    }
	
	private class SessionStatusCallback implements Session.StatusCallback {
		@Override
        public void call(Session sesion, SessionState estado, Exception excepcion) {
			onSessionStateChange(sesion, estado, excepcion);
        }
	}
	
	private void onSessionStateChange(final Session sesion, SessionState estado, Exception excepcion) {
		if (sesion != null && sesion.isOpened()) {
	    	actualizarView();
	    }
	}
	
	@Override
	public void onClick(View v) {
		Session sesion = Session.getActiveSession();
		if (sesion.isOpened()) {
			// sesion.closeAndClearTokenInformation();
			sesion.close();
			actualizarView();
		} else if (!sesion.isOpened() && !sesion.isClosed()) {
			sesion.openForRead(new Session.OpenRequest(activity).setCallback(estadoCallback));
		} else {
			Session.openActiveSession(activity, true, estadoCallback);
		}
	}
	
	public Session.StatusCallback getStatusCallback() {
		return estadoCallback;
	}
	
	public void onClick(DialogInterface arg0, int arg1) {
		// TODO Auto-generated method stub
	}
}